package dk.rhok.server;

import java.util.ArrayList;

import dk.rhok.model.Assessment;
import dk.rhok.model.Coordinate;
import dk.rhok.model.DangerZone;
import dk.rhok.model.DangerZoneImpl;
import dk.rhok.model.MapOverlay;
import dk.rhok.model.ShelterAssessmentImpl;

/**
 * Respons to requests for map overlays
 * 
 * @author Jonas Grann <jonasgrann@gmail.com>
 * @since 0.1
 */

public class MapOverlayServerImpl implements MapOverlayServer {
	
	// Arraylist for demo purpose
	ArrayList<MapOverlay> overlays = new ArrayList<MapOverlay>();
	
	public MapOverlayServerImpl (){
		// As this is a demo server, some demo data is added
		Assessment a = new ShelterAssessmentImpl(0, 18.539269, -72.336408, 100, 1000, 10000, 10, 100, 23, 44);
		
		// Add an example map overlay
		DangerZone zone = new DangerZoneImpl("Warning here!");
		zone.addPoint(new Coordinate(18.539269, -72.336408));
		zone.addPoint(new Coordinate(18.539272, -72.336410));
		zone.addPoint(new Coordinate(18.539277, -72.336412));
		
		overlays.add(a);
		overlays.add(zone);
		
	}

	public void addMapOverlay (MapOverlay o){
		overlays.add(o);
	}
	
	public ArrayList<MapOverlay> getOverlays(Coordinate from, Coordinate to,
			String types) {
		
		ArrayList<MapOverlay> overlaysInArea = new ArrayList<MapOverlay>();
		
		// Find the assessments in the area
		for(MapOverlay a : overlays){
			Coordinate point = new Coordinate(a.latitude(), a.longitude());
			if(pointInArea(from, to, point) && (types.contains(a.getType()) || types.contains("all"))){
				overlaysInArea.add(a);
			}
		}
		
		return overlaysInArea;
	}
	
	/**
	 * Checks if a given point is within a given area
	 * @param from
	 * @param to
	 * @param point
	 * @return
	 */
	private boolean pointInArea(Coordinate from, Coordinate to, Coordinate point){
		return (point.getLatitude()>from.getLatitude() && point.getLatitude() > from.getLatitude() && point.getLatitude() < to.getLatitude() && point.getLongitude() < to.getLongitude());
	}
}
